<template>
  <el-dialog
    v-model="dialogVisible"
    :title="isView ? '查看气象数据' : (formData ? '编辑气象数据' : '新增气象数据')"
    width="800px"
    :close-on-click-modal="false"
  >
    <el-form
      ref="formRef"
      :model="form"
      :rules="rules"
      label-width="120px"
      :disabled="isView"
    >
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="监测站点" prop="stationId">
            <el-select
              v-model="form.stationId"
              placeholder="请选择监测站点"
              style="width: 100%"
            >
              <el-option
                v-for="station in weatherStations"
                :key="station.id"
                :label="station.name"
                :value="station.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="记录时间" prop="recordTime">
            <el-date-picker
              v-model="form.recordTime"
              type="datetime"
              placeholder="选择记录时间"
              format="YYYY-MM-DD HH:mm"
              value-format="YYYY-MM-DD HH:mm:ss"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="温度(°C)" prop="temperature">
            <el-input-number
              v-model="form.temperature"
              :precision="1"
              :step="0.1"
              :min="-50"
              :max="60"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="湿度(%)" prop="humidity">
            <el-input-number
              v-model="form.humidity"
              :min="0"
              :max="100"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="降雨量(mm)" prop="rainfall">
            <el-input-number
              v-model="form.rainfall"
              :precision="1"
              :step="0.1"
              :min="0"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="风速(m/s)" prop="windSpeed">
            <el-input-number
              v-model="form.windSpeed"
              :precision="1"
              :step="0.1"
              :min="0"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="风向" prop="windDirection">
            <el-select
              v-model="form.windDirection"
              placeholder="请选择风向"
              style="width: 100%"
            >
              <el-option label="北风" value="北风" />
              <el-option label="东北风" value="东北风" />
              <el-option label="东风" value="东风" />
              <el-option label="东南风" value="东南风" />
              <el-option label="南风" value="南风" />
              <el-option label="西南风" value="西南风" />
              <el-option label="西风" value="西风" />
              <el-option label="西北风" value="西北风" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="气压(hPa)" prop="pressure">
            <el-input-number
              v-model="form.pressure"
              :precision="1"
              :step="0.1"
              :min="800"
              :max="1200"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="能见度(km)" prop="visibility">
            <el-input-number
              v-model="form.visibility"
              :precision="1"
              :step="0.1"
              :min="0"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="天气状况" prop="weather">
            <el-select
              v-model="form.weather"
              placeholder="请选择天气状况"
              style="width: 100%"
            >
              <el-option label="晴" value="晴" />
              <el-option label="多云" value="多云" />
              <el-option label="阴" value="阴" />
              <el-option label="小雨" value="小雨" />
              <el-option label="中雨" value="中雨" />
              <el-option label="大雨" value="大雨" />
              <el-option label="暴雨" value="暴雨" />
              <el-option label="雷阵雨" value="雷阵雨" />
              <el-option label="雪" value="雪" />
              <el-option label="雾" value="雾" />
              <el-option label="霾" value="霾" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="数据来源" prop="dataSource">
            <el-select
              v-model="form.dataSource"
              placeholder="请选择数据来源"
              style="width: 100%"
            >
              <el-option label="自动监测" value="自动监测" />
              <el-option label="人工观测" value="人工观测" />
              <el-option label="卫星数据" value="卫星数据" />
              <el-option label="雷达数据" value="雷达数据" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="数据质量" prop="dataQuality">
            <el-select
              v-model="form.dataQuality"
              placeholder="请选择数据质量"
              style="width: 100%"
            >
              <el-option label="优" value="优" />
              <el-option label="良" value="良" />
              <el-option label="中" value="中" />
              <el-option label="差" value="差" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="观测员" prop="observer">
            <el-input
              v-model="form.observer"
              placeholder="请输入观测员姓名"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="联系电话" prop="phone">
            <el-input
              v-model="form.phone"
              placeholder="请输入联系电话"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <el-form-item label="备注" prop="remark">
        <el-input
          v-model="form.remark"
          type="textarea"
          :rows="3"
          placeholder="请输入备注信息"
        />
      </el-form-item>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleCancel">取消</el-button>
        <el-button v-if="!isView" type="primary" @click="handleSubmit">
          确定
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, watch, computed } from 'vue'
import { ElMessage } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'

interface Props {
  visible: boolean
  formData?: any
  isView?: boolean
}

interface Emits {
  (e: 'update:visible', visible: boolean): void
  (e: 'success'): void
}

const props = withDefaults(defineProps<Props>(), {
  visible: false,
  formData: null,
  isView: false
})

const emit = defineEmits<Emits>()

// 监测站点
const weatherStations = ref([
  { id: 1, name: '西音水库主站' },
  { id: 2, name: '大坝监测站' },
  { id: 3, name: '库区中心站' },
  { id: 4, name: '入库口站' },
  { id: 5, name: '出库口站' }
])

// 表单引用
const formRef = ref<FormInstance>()

// 表单数据
const form = reactive({
  id: null,
  stationId: '',
  recordTime: '',
  temperature: null,
  humidity: null,
  rainfall: null,
  windSpeed: null,
  windDirection: '',
  pressure: null,
  visibility: null,
  weather: '',
  dataSource: '',
  dataQuality: '',
  observer: '',
  phone: '',
  remark: ''
})

// 表单验证规则
const rules: FormRules = {
  stationId: [
    { required: true, message: '请选择监测站点', trigger: 'change' }
  ],
  recordTime: [
    { required: true, message: '请选择记录时间', trigger: 'change' }
  ],
  temperature: [
    { required: true, message: '请输入温度', trigger: 'blur' }
  ],
  humidity: [
    { required: true, message: '请输入湿度', trigger: 'blur' }
  ],
  windDirection: [
    { required: true, message: '请选择风向', trigger: 'change' }
  ],
  weather: [
    { required: true, message: '请选择天气状况', trigger: 'change' }
  ],
  dataSource: [
    { required: true, message: '请选择数据来源', trigger: 'change' }
  ]
}

// 弹窗显示状态
const dialogVisible = computed({
  get: () => props.visible,
  set: (value) => emit('update:visible', value)
})

// 重置表单
const resetForm = () => {
  Object.assign(form, {
    id: null,
    stationId: '',
    recordTime: '',
    temperature: null,
    humidity: null,
    rainfall: null,
    windSpeed: null,
    windDirection: '',
    pressure: null,
    visibility: null,
    weather: '',
    dataSource: '',
    dataQuality: '',
    remark: ''
  })
  formRef.value?.clearValidate()
}

// 监听表单数据变化
watch(
  () => props.formData,
  (newData) => {
    if (newData) {
      Object.assign(form, newData)
    } else {
      resetForm()
    }
  },
  { immediate: true }
)

// 模拟API - 保存气象数据
const saveWeatherData = async (data: any) => {
  try {
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 1000))
    return { success: true }
  } catch (error) {
    throw new Error('保存失败')
  }
}

// 模拟API - 更新气象数据
const updateWeatherData = async (data: any) => {
  try {
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 1000))
    return { success: true }
  } catch (error) {
    throw new Error('更新失败')
  }
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return

  try {
    await formRef.value.validate()
    
    if (form.id) {
      await updateWeatherData(form)
      ElMessage.success('更新成功')
    } else {
      await saveWeatherData(form)
      ElMessage.success('新增成功')
    }
    
    emit('success')
    dialogVisible.value = false
  } catch (error) {
    if (error instanceof Error) {
      ElMessage.error(error.message)
    }
  }
}

// 取消
const handleCancel = () => {
  dialogVisible.value = false
}
</script>

<style scoped>
.dialog-footer {
  text-align: right;
}
</style>